<!-- 树组件 -->
<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { PropType } from 'vue'
// import { ElTree as MyElTree } from 'element-plus'
import type { ElTree as MyElTree } from 'element-plus'

const emits = defineEmits(['nodeClick'])

const myProps = defineProps({
  nodeKey: {
    type: String,
    default: 'id'
  },
  multiple: {
    type: Boolean,
    default: false
  },
  // 数据
  data: {
    type: Array as PropType<any[]>,
    default() {
      return [] as any[]
    }
  },
  // 属性映射
  props: {
    type: Object,
    default() {
      return {}
    }
  },
  // 是否父子不关联
  checkStrictly: {
    type: Boolean,
    default: false
  },
  // 是否显示勾选框
  showCheckbox: {
    type: Boolean,
    default: false
  },
  // 默认选中的节点
  defaultCheckedKeys: {
    type: Array,
    default() {
      return []
    }
  },
  // 搜索框高度
  searchHeight: {
    type: String,
    default: '32px'
  },
  // 是否有搜索框
  search: {
    type: Boolean,
    default: true
  }
})

// 树ref
const treeRef = ref<InstanceType<typeof MyElTree>>()
// 树数据过滤关键字
const filterText = ref('')

watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

/**
 * 点击选择节点
 */
function handleNodeClick(curNode: any, allData: any) {
  // 多选
  if (myProps.multiple) {
    emits('nodeClick', allData)
  }
  // 单选
  else {
    if (allData.checkedKeys?.length) {
      treeRef.value?.setCheckedKeys([String(curNode[myProps.nodeKey])])
    } else {
      treeRef.value?.setCheckedKeys([])
    }
    emits('nodeClick', curNode)
  }
}
/**
 * 树数据过滤方法
 */
function filterNodeFunc(text: string, data: any) {
  if (!text) {
    return true
  }
  const label = myProps.props.label ?? 'label'
  return data[label].includes(text)
}
/**
 * 获取选中节点keys
 */
function getCheckedKeys(flag: boolean = false) {
  const pickList = treeRef.value?.getCheckedKeys(flag) || []
  return pickList
}
/**
 * 设置选中节点key
 */
function setCheckedKeys(list: string[]) {
  treeRef.value?.setCheckedKeys(list)
}

defineExpose({
  getCheckedKeys,
  setCheckedKeys
})
</script>

<template>
  <div class="dui-tree-bg">
    <div class="dui-tree-search" :style="{ height: searchHeight }" v-if="search">
      <el-input v-model="filterText" placeholder="关键字过滤" clearable style="height: 100%" />
    </div>
    <div class="dui-tree-body" :style="{ height: `calc(100% - ${search ? searchHeight : '0px'})` }">
      <el-tree ref="treeRef" v-bind="myProps" node-key="id" :filter-node-method="filterNodeFunc" @check="handleNodeClick" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dui-tree-bg {
  height: 100%;
  .dui-tree-search {
  }
  .dui-tree-body {
    margin-top: 4px;
    box-sizing: border-box;
    padding-bottom: 10px;
    overflow-y: auto;
  }
}
</style>
